#include "myio.h"
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
const int  DFL_MODE = 0666;
myFILE* my_fopen(const char* path,const char* mode)
{
    int fd = 0;
    int flag = 0;
    if(strcmp(mode,"r")==0)
     {
        flag |= O_RDONLY; 
     }
    else if(strcmp(mode,"w")==0)
    {
        flag |= (O_CREAT | O_TRUNC | O_WRONLY);
    }
    else if(strcmp(mode,"a")==0)
    {
        flag |= (O_CREAT |O_WRONLY | O_APPEND);
    }
    else {
        //nothing to do
    }
    

    if(flag & O_CREAT)
    {
        fd = open(path,flag,DFL_MODE);
    }
    else{
        fd = open(path,flag);
    }
    if(fd<0)
    {
        return NULL;
    }
    myFILE* fp =(myFILE*) malloc(sizeof(myFILE));
    if(fp==NULL)
    {
        return NULL;
    }
    memset(fp->buffer,'\0',SIZE);
    fp->flag = FLLUSH_LINE;
    fp->lenth = 0;
    fp->fileno = fd;
    return fp;
}

int my_fflush(myFILE* stream)
{
    if(stream->lenth>0)
    {
        write(stream->fileno,stream->buffer,stream->lenth);
        stream->lenth = 0;
        stream->buffer[0] = 0;
    }
    return 0;
}

int my_fclose(myFILE* stream)
{
    my_fflush(stream);
       close(stream->fileno);
    free(stream);
    return 0;
}

myFILE* my_fwrite(const char* s,myFILE* stream)
{
    strcat(stream->buffer,s);
    stream->lenth+=strlen(s);
    if(stream->lenth>0 && (stream->flag&FLLUSH_LINE) && stream->buffer[stream->lenth-1]=='\n')
    {
        my_fflush(stream);
    }
    return stream;
}

int main()
{
    myFILE* fp = my_fopen("log.txt","w");
    fp->flag = FLLUSH_LINE;
    char str[100] = " ::this is my write\n";
    int count =5;
    while(count--)
    {
        sleep(1);
        str[0] = count+'0';
        my_fwrite(str,fp);
    }
    my_fclose(fp);

    return 0;
}

//#include <stdio.h>
//#include <unistd.h>
//#include <string.h>
//int main(){
//    fprintf(stdout,"this is printed by fprintf\n");
//    printf("this is printed by printf\n");
//    fputs("this is printed by puts\n",stdout);
//    const char* str = "this is printed by system call\n";
//    write(1,str,strlen(str));
//    
//    fork();
//    return 0;
//}
